/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.supplier;

import ejb.model.EJBModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.DefaultComboBoxModel;
import util.person.address.CountryDetails;

/**
 *
 * @author Gebruiker
 */
public class CountryComboBoxModel extends DefaultComboBoxModel {
    
    private ArrayList<CountryDetails> countries;
    private ArrayList<String> specialCountries;
    
    public CountryComboBoxModel(){
        countries = new ArrayList<CountryDetails>();
        for(CountryDetails country:EJBModel.getCountryBean().getAllCountryDetails()){
            countries.add(country);
        }
        specialCountries = new ArrayList<String>();
        specialCountries.add("BE");
        specialCountries.add("NL");
        specialCountries.add("FR");
        specialCountries.add("LU");
        specialCountries.add("DE");
        specialCountries.add("GB");
        
        Collections.sort(countries, new CountryComparator());
    }

    @Override
    public int getSize() {
        return countries.size();
    }

    @Override
    public Object getElementAt(int index) {
        CountryDetails country = countries.get(index);
        String value = country.getName() +" ("+country.getCountryCode()+")";
        return value;
    }
    
    public int getId(int selected){
        return countries.get(selected).getId();
    }

    public int getIndexOf(Integer number) {
        int i = 0;
        for(CountryDetails country:countries){
            if(country.getId().equals(number)){
                return i;
            }
            i++;
        }
        return 0;
    }
    
    
    
    private class CountryComparator implements Comparator{

        @Override
        public int compare(Object o1, Object o2) {
            CountryDetails country1 = (CountryDetails) o1;
            CountryDetails country2 = (CountryDetails) o2;
            String code1 = country1.getCountryCode();
            String code2 = country2.getCountryCode();
            if(specialCountries.contains(code1) && specialCountries.contains(code2)){
                Integer index1 = specialCountries.indexOf(code1);
                Integer index2 = specialCountries.indexOf(code2);
                return index1.compareTo(index2);    
            } else if(specialCountries.contains(code1)){
                return -1;
            } else if(specialCountries.contains(code2)){
                return 1;
            } else{
                return country1.getName().compareTo(country2.getName());
            }
        }  
    }
    
    
    
}
